/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import { pickedFaceData, pickedLineData, pickedVertexData } from '@amcax/base';
import { previewer } from '@app-cad/module';
import {
  NumberInputFormat,
  PickInputRJSFFormat,
} from '@app-cad/common/components/command-form/constants';
import { NonDialogPickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import { getIdOfPickedObj } from '@app-cad/common/utils/render';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import { useState } from 'react';
import { ChildLineCommandProps } from './types';

type FormData = {
  start?: pickedVertexData;
  vector?: pickedLineData | pickedFaceData;
  forwardDistance: number;
  backDistance: number;
};

type Params = {
  mode: 'vector';
  origin: string;
  vector: string;
  forward: number;
  back: number;
};

export const AlignVector = ({
  onClose,
  props,
  editDxid,
}: ChildLineCommandProps) => {
  const initData = {
    forwardDistance: 60,
    backDistance: 0,
  };

  const [formData, setFormData] = useState<FormData>(initData);

  const { picker } = useTools();

  useAsyncEffect(async () => {
    if (props == null) {
      setFormData(initData);
      return;
    }

    const params: Params = props.params;
    const { origin, vector, forward, back } = params;

    await initEditDependency([origin, vector]);

    const startPoint = picker.generatePickObjByPickID(
      origin,
    ) as pickedVertexData;

    setFormData({
      start: startPoint,
      vector: picker.generatePickObjByPickID(vector, { showArrow: true }) as
        | pickedLineData
        | pickedFaceData,
      forwardDistance: forward,
      backDistance: back,
    });
  }, [editDxid]);

  const checkAndFinishDraw = async () => {
    if (!isFormDataValid()) {
      return;
    }

    execute(false);

    onClose();
  };

  const { initEditDependency, initingEdit, confirmCommand } = useCommand(
    'cmd-line-dot-align-vector',
    {
      onClose,
      finishDraw: checkAndFinishDraw,
      commandName: 'CreateCurve',
      editDxid,
    },
  );

  const execute = async (preview: boolean) => {
    const { start, vector, forwardDistance, backDistance } = formData;
    const params = {
      type: 'Line',
      a: {
        mode: 'vector',
        origin: start.vertexId,
        vector: getIdOfPickedObj(vector),
        forward: forwardDistance,
        back: backDistance,
      },
    };

    await confirmCommand(params, preview);
  };

  const isFormDataValid = () => {
    const { vector, start, forwardDistance, backDistance } = formData;

    return (
      vector != null &&
      start != null &&
      forwardDistance != null &&
      backDistance != null &&
      forwardDistance !== -backDistance
    );
  };

  useAsyncEffect(async () => {
    if (!isFormDataValid()) {
      previewer.clear();
      return;
    }

    await execute(true);
  }, [formData]);

  const schema: RJSFSchema = {
    type: 'object',
    properties: {
      start: {
        type: 'string',
        format: PickInputRJSFFormat.PickVertex,
      },
      vector: {
        type: 'string',
        format: PickInputRJSFFormat.PickDirection,
      },
      forwardDistance: {
        type: 'number',
        title: '向前偏移',
        format: NumberInputFormat.Length,
      },
      backDistance: {
        type: 'number',
        title: '向后偏移',
        default: 0,
        format: NumberInputFormat.Length,
      },
    },
  };

  return (
    <NonDialogPickableCommandForm
      className='-mt-3'
      disabled={initingEdit}
      onCancel={onClose}
      schema={schema}
      formData={formData}
      onChange={(v) => {
        setFormData(v);
      }}
      isFormDataValid={isFormDataValid()}
      extraUiSchema={{
        start: {
          'ui:placeholder': '请输入起点',
          'ui:autofocus': true,
        },
        vector: {
          'ui:placeholder': '请输入方向',
          'ui:options': {
            showArrow: true,
          },
        },
        fowardDistance: {
          'ui:placeholder': '请输入距离',
        },
        backDistance: {
          'ui:placeholder': '请输入距离',
        },
      }}
      submitText='完成'
      onSubmit={checkAndFinishDraw}
    />
  );
};
